package com.dragon.mmochat.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import com.dragon.mmochat.model.gang.MmochatGang;
import com.dragon.mmochat.model.pkteam.MmochatPkTeam;
import com.dragon.mmochat.model.pkteam.MmochatPkTeamMember;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class MmochatPkTeamDao extends SimpleJdbcDaoSupport {
	private static final GangRowMapper pkTeamMapper = new GangRowMapper();

	// 创建战队
	private static final String createPkTeamSql = "insert into pkteam(name, members, createtime) "
			+ "values(?, ?, ?)";

	public void createPkTeam(String gSon_members, String name) {
		getSimpleJdbcTemplate().update(createPkTeamSql, name, gSon_members,
				new Timestamp(System.currentTimeMillis()));
	}

	// 查找指定名字的战队
	private static final String getPkTeamByNameSql = "select * from pkteam where name = ?";

	public MmochatPkTeam getPkTeamByName(String name) {
		return getSimpleJdbcTemplate().queryForObject(getPkTeamByNameSql,
				pkTeamMapper, name);
	}

	// 查找指定id的战队
	private static final String getPkTeamByIdSql = "select * from pkteam where id = ?";

	public MmochatPkTeam getPkTeamById(int id) {
		return getSimpleJdbcTemplate().queryForObject(getPkTeamByIdSql,
				pkTeamMapper, id);
	}

	public int commonUpdate(String sql) {
		return getSimpleJdbcTemplate().update(sql);
	}

	public List<MmochatPkTeam> commonQuery(String sql) {
		return getSimpleJdbcTemplate().query(sql, pkTeamMapper);
	}

	public MmochatPkTeam commonQueryForObject(String sql) {
		return getSimpleJdbcTemplate().queryForObject(sql, pkTeamMapper);
	}

	static class GangRowMapper implements ParameterizedRowMapper<MmochatPkTeam> {
		@Override
		public MmochatPkTeam mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			MmochatPkTeam team = new MmochatPkTeam();
			team.setId(rs.getInt("id"));
			team.setName(rs.getString("name"));
			team.setScore(rs.getInt("score"));

			// TODO:GSON
			Gson gson = new Gson();

			String str = rs.getString("members");
			if (str != null) {
				Map<Integer, MmochatPkTeamMember> members = gson.fromJson(str,
						new TypeToken<Map<Integer, MmochatPkTeamMember>>() {
						}.getType());
				if (members != null) {
					team.setMembers(members);
				}
			}
			return team;
		}
	}
}
